var http = require('http');
var qs = require('querystring');

var defaultOptions = {
    hostname: '127.0.0.1',
    port: 8888,
    agent: new http.Agent({keepAlive: true, maxSockets: 2}),
    headers: {
        'Connection': 'Keep-Alive',
        //'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        'Content-Type': 'application/json'
    }
};

var getOptions = function (obj) {
    var result = {};
    for (var key in defaultOptions) {
        result[key] = defaultOptions[key];
    }
    for (var key in obj) {
        result[key] = obj[key];
    }
    return result;
};

/************************** 模拟 get 请求 ******************************/

var getData = function () {

    var options = getOptions({
        path: '/services/user/1234.json?' + qs.stringify({id: 100}),
        method: 'GET'
    });

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.end();
};

getData();

/************************** 模拟 post 请求 ******************************/

var postData = function () {

    var options = getOptions({
        path: '/services/user/register.json',
        method: 'POST'
    });

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.write(JSON.stringify({id: 123, username: 'Tom'}));

    req.end();
};

postData();